package com.gp.billsrecord.ui.main.fragments

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.gp.billsrecord.R
import com.gp.billsrecord.databinding.FragmentMainAccountSettingBinding
import com.gp.billsrecord.base.BaseFragment
import com.gp.billsrecord.base.Const
import com.gp.billsrecord.ui.main.adapters.AccountAdapter
import com.gp.billsrecord.vm.AppViewModel
import com.xujichang.base.extensions.findNavController
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/*账户*/
class AccountManagerFragment : BaseFragment<FragmentMainAccountSettingBinding>() {
    private val accountAdapter = AccountAdapter()
    private val viewModel by viewModels<AppViewModel>()
    override fun onBindingCreated() {
        //初始化列表view
        binding.rvAccounts.also { recyclerView ->
            recyclerView.layoutManager = LinearLayoutManager(requireContext())
            recyclerView.adapter = accountAdapter
        }
        //点击添加账户
        binding.btnAddAccount.setOnClickListener {
            //添加账户
            addAccount()
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        viewLifecycleOwner.lifecycleScope.launch {
            //监听当前用户的账户信息
            viewModel.observeAccounts().collectLatest(accountAdapter::submitData)
        }
    }

    private fun addAccount() {
        //跳转到添加账户的弹框
        findNavController(Const.LABEL_APP).navigate(R.id.accountAddDialog)
    }
}